﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using BanZuiCloudControlAgent.Utils.Common;
using BanZuiCloudControlAgent.Utils.Logging;
using Microsoft.Win32;

namespace BanZuiCloudControlAgent.Utils.Common
{
    /// <summary>
    /// 系统信息工具类，提供获取系统各项信息的功能
    /// </summary>
    public static class SystemInfo
    {
        private static readonly Logger _logger = LogManager.GetLogger(nameof(SystemInfo));
        
        // 用于获取公网IP的API列表
        private static readonly string[] _publicIpApis = new string[] 
        {
            "https://ipv4.icanhazip.com",
            "https://v4.ident.me",
            "https://checkip.amazonaws.com",
            "https://icanhazip.com",
            "https://ifconfig.co/ip",
            "https://ipinfo.io/ip",
            "https://wtfismyip.com/text",
            "https://ipecho.net/plain",
            "https://myip.dnsomatic.com"
        };
        
        // 用于随机化API选择的随机数生成器
        private static readonly Random _random = new Random();
        
        // 已尝试过的API索引集合
        private static HashSet<int> _triedApiIndices = new HashSet<int>();

        #region 基本系统信息

        /// <summary>
        /// 获取操作系统名称和版本
        /// </summary>
        /// <returns>操作系统名称和版本</returns>
        public static string GetOSVersion()
        {
            try
            {
                string osName = string.Empty;
                string osVersion = string.Empty;
                string osArchitecture = Environment.Is64BitOperatingSystem ? "64位" : "32位";

                // 从注册表获取系统信息
                using (
                    RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(
                        @"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                    )
                )
                {
                    if (registryKey != null)
                    {
                        osName = registryKey.GetValue("ProductName")?.ToString() ?? "未知";
                        // 获取版本信息
                        var buildNumber = registryKey.GetValue("CurrentBuildNumber")?.ToString();
                        var releaseId = registryKey.GetValue("ReleaseId")?.ToString();

                        osVersion = !string.IsNullOrEmpty(releaseId)
                            ? $"版本 {releaseId} (Build {buildNumber})"
                            : $"Build {buildNumber}";
                    }
                }

                return $"{osName} {osVersion} {osArchitecture}";
            }
            catch (Exception ex)
            {
                _logger.Error($"获取操作系统信息失败: {ex.Message}");
                return "获取操作系统信息失败";
            }
        }

        /// <summary>
        /// 获取计算机名称
        /// </summary>
        /// <returns>计算机名称</returns>
        public static string GetComputerName()
        {
            try
            {
                return Environment.MachineName;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取计算机名称失败: {ex.Message}");
                return "获取计算机名称失败";
            }
        }

        /// <summary>
        /// 获取当前登录用户名
        /// </summary>
        /// <returns>当前登录用户名</returns>
        public static string GetUserName()
        {
            try
            {
                return Environment.UserName;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取用户名失败: {ex.Message}");
                return "获取用户名失败";
            }
        }

        /// <summary>
        /// 获取系统运行时间(单位:小时)
        /// </summary>
        /// <returns>系统运行时间(小时)</returns>
        public static double GetSystemUptime()
        {
            try
            {
                // 获取系统启动时间的毫秒数
                int tickCount = Environment.TickCount;
                // 转换为小时
                double uptimeHours = tickCount / (1000.0 * 60 * 60);
                return Math.Round(uptimeHours, 2);
            }
            catch (Exception ex)
            {
                _logger.Error($"获取系统运行时间失败: {ex.Message}");
                return -1;
            }
        }

        #endregion

        #region CPU信息

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns>CPU信息</returns>
        public static string GetCpuInfo()
        {
            try
            {
                using (
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                        "SELECT * FROM Win32_Processor"
                    )
                )
                {
                    StringBuilder cpuInfo = new StringBuilder();
                    foreach (ManagementObject obj in searcher.Get())
                    {
                        cpuInfo.AppendLine($"名称: {obj["Name"]}");
                        cpuInfo.AppendLine($"制造商: {obj["Manufacturer"]}");
                        cpuInfo.AppendLine($"频率: {obj["MaxClockSpeed"]} MHz");
                        cpuInfo.AppendLine($"内核数: {obj["NumberOfCores"]}");
                        cpuInfo.AppendLine($"逻辑处理器数: {obj["NumberOfLogicalProcessors"]}");
                        break; // 通常只获取一个CPU信息
                    }
                    return cpuInfo.ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"获取CPU信息失败: {ex.Message}");
                return "获取CPU信息失败";
            }
        }

        /// <summary>
        /// 获取CPU使用率
        /// </summary>
        /// <returns>CPU使用率百分比</returns>
        public static float GetCpuUsage()
        {
            try
            {
                PerformanceCounter cpuCounter = new PerformanceCounter(
                    "Processor",
                    "% Processor Time",
                    "_Total"
                );
                // 第一次读取通常返回0，需要等待一段时间后再次读取
                cpuCounter.NextValue();
                System.Threading.Thread.Sleep(1000);
                return cpuCounter.NextValue();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取CPU使用率失败: {ex.Message}");
                return -1;
            }
        }

        #endregion

        #region 内存信息

        /// <summary>
        /// 获取物理内存信息
        /// </summary>
        /// <returns>物理内存信息</returns>
        public static string GetMemoryInfo()
        {
            try
            {
                using (
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                        "SELECT * FROM Win32_ComputerSystem"
                    )
                )
                {
                    foreach (ManagementObject obj in searcher.Get())
                    {
                        // 获取总物理内存(单位:GB)
                        double totalMemoryGB =
                            Convert.ToDouble(obj["TotalPhysicalMemory"]) / (1024 * 1024 * 1024);
                        return $"总物理内存: {totalMemoryGB:F2} GB";
                    }
                    return "未能获取内存信息";
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"获取内存信息失败: {ex.Message}");
                return "获取内存信息失败";
            }
        }

        /// <summary>
        /// 获取内存使用情况
        /// </summary>
        /// <returns>内存使用情况信息</returns>
        public static MemoryMetrics GetMemoryUsage()
        {
            try
            {
                // 使用PerformanceCounter获取内存信息
                using (
                    PerformanceCounter ramCounter = new PerformanceCounter(
                        "Memory",
                        "Available MBytes"
                    )
                )
                {
                    // 获取可用内存(MB)
                    float availableMB = ramCounter.NextValue();

                    // 获取总物理内存
                    ulong totalMemoryMB = 0;
                    using (
                        ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                            "SELECT * FROM Win32_ComputerSystem"
                        )
                    )
                    {
                        foreach (ManagementObject obj in searcher.Get())
                        {
                            // 获取总物理内存(单位:MB)
                            totalMemoryMB =
                                Convert.ToUInt64(obj["TotalPhysicalMemory"]) / (1024 * 1024);
                            break;
                        }
                    }

                    // 计算已使用内存和使用率
                    ulong usedMemoryMB = totalMemoryMB - (ulong)availableMB;
                    uint usagePercentage =
                        totalMemoryMB > 0 ? (uint)((usedMemoryMB * 100) / totalMemoryMB) : 0;

                    _logger.Debug(
                        $"使用PerformanceCounter获取内存信息成功：总内存={totalMemoryMB}MB, 已用={usedMemoryMB}MB, 使用率={usagePercentage}%"
                    );

                    return new MemoryMetrics
                    {
                        Total = totalMemoryMB,
                        Used = usedMemoryMB,
                        UsagePercentage = usagePercentage,
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"获取内存使用情况失败: {ex.Message}");
                return new MemoryMetrics
                {
                    Total = 0,
                    Used = 0,
                    UsagePercentage = 0,
                };
            }
        }

        /// <summary>
        /// 内存使用指标类
        /// </summary>
        public class MemoryMetrics
        {
            /// <summary>
            /// 总内存(MB)
            /// </summary>
            public ulong Total { get; set; }

            /// <summary>
            /// 已使用内存(MB)
            /// </summary>
            public ulong Used { get; set; }

            /// <summary>
            /// 内存使用百分比
            /// </summary>
            public uint UsagePercentage { get; set; }

            /// <summary>
            /// 可用内存(MB)
            /// </summary>
            public ulong Available => Total - Used;
        }

        // 定义内存状态结构体
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private class MEMORYSTATUSEX
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public ulong ullTotalPhys;
            public ulong ullAvailPhys;
            public ulong ullTotalPageFile;
            public ulong ullAvailPageFile;
            public ulong ullTotalVirtual;
            public ulong ullAvailVirtual;
            public ulong ullAvailExtendedVirtual;
        }

        // 导入GlobalMemoryStatusEx函数
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);

        #endregion

        #region 磁盘信息

        /// <summary>
        /// 获取C盘空间使用百分比
        /// </summary>
        /// <returns>C盘空间使用百分比</returns>
        public static double GetCDriveUsagePercentage()
        {
            try
            {
                // 获取C盘信息
                DriveInfo cDrive = new DriveInfo("C");
                
                // 检查驱动器是否准备好
                if (cDrive.IsReady)
                {
                    // 计算使用百分比
                    double usagePercentage = Math.Round(
                        ((double)(cDrive.TotalSize - cDrive.AvailableFreeSpace) / cDrive.TotalSize) * 100,
                        2
                    );
                    
                    return usagePercentage;
                }
                else
                {
                    _logger.Error("C盘未准备好，无法获取使用率");
                    return -1;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"获取C盘空间使用百分比失败: {ex.Message}");
                return -1;
            }
        }

        /// <summary>
        /// 获取磁盘信息
        /// </summary>
        /// <returns>磁盘信息列表</returns>
        public static List<DiskInfo> GetDiskInfo()
        {
            try
            {
                List<DiskInfo> diskInfoList = new List<DiskInfo>();

                // 获取所有驱动器信息
                DriveInfo[] drives = DriveInfo.GetDrives();

                foreach (DriveInfo drive in drives)
                {
                    // 只处理准备好的驱动器
                    if (drive.IsReady)
                    {
                        DiskInfo diskInfo = new DiskInfo
                        {
                            Name = drive.Name,
                            VolumeLabel = drive.VolumeLabel,
                            DriveType = drive.DriveType.ToString(),
                            DriveFormat = drive.DriveFormat,
                            TotalSizeGB = Math.Round(
                                (double)drive.TotalSize / (1024 * 1024 * 1024),
                                2
                            ),
                            AvailableFreeSpaceGB = Math.Round(
                                (double)drive.AvailableFreeSpace / (1024 * 1024 * 1024),
                                2
                            ),
                            UsedSpaceGB = Math.Round(
                                (double)(drive.TotalSize - drive.AvailableFreeSpace)
                                    / (1024 * 1024 * 1024),
                                2
                            ),
                            UsagePercentage = Math.Round(
                                (
                                    (double)(drive.TotalSize - drive.AvailableFreeSpace)
                                    / drive.TotalSize
                                ) * 100,
                                2
                            ),
                        };

                        diskInfoList.Add(diskInfo);
                    }
                }

                return diskInfoList;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取磁盘信息失败: {ex.Message}");
                return new List<DiskInfo>();
            }
        }

        /// <summary>
        /// 磁盘信息类
        /// </summary>
        public class DiskInfo
        {
            /// <summary>
            /// 驱动器名称
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 卷标
            /// </summary>
            public string VolumeLabel { get; set; }

            /// <summary>
            /// 驱动器类型
            /// </summary>
            public string DriveType { get; set; }

            /// <summary>
            /// 文件系统格式
            /// </summary>
            public string DriveFormat { get; set; }

            /// <summary>
            /// 总大小(GB)
            /// </summary>
            public double TotalSizeGB { get; set; }

            /// <summary>
            /// 可用空间(GB)
            /// </summary>
            public double AvailableFreeSpaceGB { get; set; }

            /// <summary>
            /// 已使用空间(GB)
            /// </summary>
            public double UsedSpaceGB { get; set; }

            /// <summary>
            /// 使用率(%)
            /// </summary>
            public double UsagePercentage { get; set; }
        }

        #endregion

        #region 网络信息
        
        /// <summary>
        /// 获取本地IP地址
        /// </summary>
        /// <returns>本地IP地址</returns>
        public static string GetLocalIpAddress()
        {
            try
            {
                // 使用SystemInfo工具类获取IP地址
                var adapters = GetNetworkAdapterInfo();
                if (adapters != null && adapters.Count > 0)
                {
                    // 优先获取有IP地址的网卡
                    var adapter = adapters.Find(a => !string.IsNullOrEmpty(a.IPv4Address));
                    if (adapter != null && !string.IsNullOrEmpty(adapter.IPv4Address))
                    {
                        return adapter.IPv4Address;
                    }
                }
                return "127.0.0.1";
            }
            catch (Exception ex)
            {
                _logger.Error($"获取本地IP地址失败: {ex.Message}");
                return "127.0.0.1";
            }
        }
        
        /// <summary>
        /// 获取公网IP地址
        /// </summary>
        /// <returns>公网IP地址</returns>
        public static string GetPublicIpAddress()
        {
            // 尝试从缓存获取公网IP
            string cacheKey = "PublicIpAddress";
            if (CacheManager.TryGet<string>(cacheKey, out string cachedIp))
            {
                _logger.Debug($"从缓存获取到公网IP地址: {cachedIp}");
                return cachedIp;
            }
            
            // 重置已尝试API索引集合
            _triedApiIndices.Clear();
            
            while (_triedApiIndices.Count < _publicIpApis.Length)
            {
                // 随机选择一个未尝试过的API
                int index;
                do
                {
                    index = _random.Next(_publicIpApis.Length);
                } while (_triedApiIndices.Contains(index));
                
                _triedApiIndices.Add(index);
                string apiUrl = _publicIpApis[index];
                
                try
                {
                    _logger.Debug($"尝试从 {apiUrl} 获取公网IP地址");
                    
                    // 创建Web请求
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
                    request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36";
                    request.Timeout = 5000; // 5秒超时
                    request.Method = "GET";
                    
                    // 获取响应
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        // 确保响应状态码为200 OK
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                string ip = reader.ReadToEnd().Trim();
                                
                                // 验证返回的是有效的IP地址
                                if (!string.IsNullOrEmpty(ip) && ip.Split('.').Length == 4)
                                {
                                    _logger.Debug($"成功获取到公网IP地址: {ip}");
                                    
                                    // 缓存IP地址，有效期10分钟
                                    CacheManager.Set(cacheKey, ip, TimeSpan.FromMinutes(10));
                                    
                                    return ip;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Debug($"从 {apiUrl} 获取公网IP地址失败: {ex.Message}");
                    // 继续尝试下一个API
                }
            }
            
            // 所有API都尝试失败，返回本地IP
            string localIp = GetLocalIpAddress();
            _logger.Error($"所有公网IP获取API都失败，返回本地IP地址: {localIp}");
            
            // 缓存本地IP，但有效期较短（1分钟）
            CacheManager.Set(cacheKey, localIp, TimeSpan.FromMinutes(1));
            
            return localIp;
        }
        
        /// <summary>
        /// 获取IP地址 (为保持兼容性，现在返回公网IP)
        /// </summary>
        public static string GetIpAddress()
        {
            return GetPublicIpAddress();
        }
        
        /// <summary>
        /// 获取网络适配器信息
        /// </summary>
        /// <returns>网络适配器信息列表</returns>
        public static List<NetworkAdapterInfo> GetNetworkAdapterInfo()
        {
            try
            {
                List<NetworkAdapterInfo> networkAdapterInfos = new List<NetworkAdapterInfo>();

                // 获取所有网络接口
                NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface networkInterface in networkInterfaces)
                {
                    // 只获取正常运行的以太网和无线接口
                    if (
                        networkInterface.OperationalStatus == OperationalStatus.Up
                        && (
                            networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet
                            || networkInterface.NetworkInterfaceType
                                == NetworkInterfaceType.Wireless80211
                        )
                    )
                    {
                        NetworkAdapterInfo adapterInfo = new NetworkAdapterInfo
                        {
                            Name = networkInterface.Name,
                            Description = networkInterface.Description,
                            Type = networkInterface.NetworkInterfaceType.ToString(),
                            Status = networkInterface.OperationalStatus.ToString(),
                            MacAddress = networkInterface.GetPhysicalAddress().ToString(),
                            SpeedMbps = networkInterface.Speed / 1000000.0,
                        };

                        // 获取IPv4地址
                        foreach (
                            UnicastIPAddressInformation ip in networkInterface
                                .GetIPProperties()
                                .UnicastAddresses
                        )
                        {
                            if (
                                ip.Address.AddressFamily
                                == System.Net.Sockets.AddressFamily.InterNetwork
                            )
                            {
                                adapterInfo.IPv4Address = ip.Address.ToString();
                                adapterInfo.SubnetMask = ip.IPv4Mask.ToString();
                                break;
                            }
                        }

                        // 获取默认网关
                        foreach (
                            GatewayIPAddressInformation gateway in networkInterface
                                .GetIPProperties()
                                .GatewayAddresses
                        )
                        {
                            if (
                                gateway.Address.AddressFamily
                                == System.Net.Sockets.AddressFamily.InterNetwork
                            )
                            {
                                adapterInfo.DefaultGateway = gateway.Address.ToString();
                                break;
                            }
                        }

                        // 获取DNS服务器
                        foreach (
                            IPAddress dnsServer in networkInterface.GetIPProperties().DnsAddresses
                        )
                        {
                            if (
                                dnsServer.AddressFamily
                                == System.Net.Sockets.AddressFamily.InterNetwork
                            )
                            {
                                adapterInfo.DnsServers.Add(dnsServer.ToString());
                            }
                        }

                        // 获取网络流量信息
                        var stats = networkInterface.GetIPv4Statistics();
                        adapterInfo.BytesReceived = stats.BytesReceived;
                        adapterInfo.BytesSent = stats.BytesSent;

                        networkAdapterInfos.Add(adapterInfo);
                    }
                }

                return networkAdapterInfos;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取网络适配器信息失败: {ex.Message}");
                return new List<NetworkAdapterInfo>();
            }
        }

        /// <summary>
        /// 网络适配器信息类
        /// </summary>
        public class NetworkAdapterInfo
        {
            /// <summary>
            /// 适配器名称
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 适配器描述
            /// </summary>
            public string Description { get; set; }

            /// <summary>
            /// 适配器类型
            /// </summary>
            public string Type { get; set; }

            /// <summary>
            /// 适配器状态
            /// </summary>
            public string Status { get; set; }

            /// <summary>
            /// MAC地址
            /// </summary>
            public string MacAddress { get; set; }

            /// <summary>
            /// IPv4地址
            /// </summary>
            public string IPv4Address { get; set; }

            /// <summary>
            /// 子网掩码
            /// </summary>
            public string SubnetMask { get; set; }

            /// <summary>
            /// 默认网关
            /// </summary>
            public string DefaultGateway { get; set; }

            /// <summary>
            /// DNS服务器列表
            /// </summary>
            public List<string> DnsServers { get; set; } = new List<string>();

            /// <summary>
            /// 连接速度(Mbps)
            /// </summary>
            public double SpeedMbps { get; set; }

            /// <summary>
            /// 已接收字节数
            /// </summary>
            public long BytesReceived { get; set; }

            /// <summary>
            /// 已发送字节数
            /// </summary>
            public long BytesSent { get; set; }
        }

        /// <summary>
        /// 测试网络连接
        /// </summary>
        /// <param name="hostNameOrAddress">主机名或IP地址</param>
        /// <returns>Ping测试结果</returns>
        public static PingResult TestConnection(string hostNameOrAddress)
        {
            try
            {
                PingResult result = new PingResult();
                result.TargetHost = hostNameOrAddress;

                using (Ping ping = new Ping())
                {
                    // 发送4个Ping包
                    int successCount = 0;
                    long totalRoundtripTime = 0;
                    long minRoundtripTime = long.MaxValue;
                    long maxRoundtripTime = 0;

                    for (int i = 0; i < 4; i++)
                    {
                        PingReply reply = ping.Send(hostNameOrAddress);

                        if (reply.Status == IPStatus.Success)
                        {
                            successCount++;
                            totalRoundtripTime += reply.RoundtripTime;

                            if (reply.RoundtripTime < minRoundtripTime)
                                minRoundtripTime = reply.RoundtripTime;

                            if (reply.RoundtripTime > maxRoundtripTime)
                                maxRoundtripTime = reply.RoundtripTime;
                        }
                    }

                    // 计算结果
                    result.PacketsSent = 4;
                    result.PacketsReceived = successCount;
                    result.PacketLossRate = Math.Round(((4 - successCount) / 4.0) * 100, 2);

                    if (successCount > 0)
                    {
                        result.MinLatency = minRoundtripTime;
                        result.MaxLatency = maxRoundtripTime;
                        result.AvgLatency = totalRoundtripTime / successCount;
                    }
                    else
                    {
                        result.MinLatency = 0;
                        result.MaxLatency = 0;
                        result.AvgLatency = 0;
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.Error($"测试网络连接失败: {ex.Message}");
                return new PingResult
                {
                    TargetHost = hostNameOrAddress,
                    PacketsSent = 4,
                    PacketsReceived = 0,
                    PacketLossRate = 100,
                    MinLatency = 0,
                    MaxLatency = 0,
                    AvgLatency = 0,
                    Error = ex.Message,
                };
            }
        }

        /// <summary>
        /// Ping测试结果类
        /// </summary>
        public class PingResult
        {
            /// <summary>
            /// 目标主机
            /// </summary>
            public string TargetHost { get; set; }

            /// <summary>
            /// 发送的数据包数量
            /// </summary>
            public int PacketsSent { get; set; }

            /// <summary>
            /// 接收的数据包数量
            /// </summary>
            public int PacketsReceived { get; set; }

            /// <summary>
            /// 数据包丢失率(%)
            /// </summary>
            public double PacketLossRate { get; set; }

            /// <summary>
            /// 最小延迟(ms)
            /// </summary>
            public long MinLatency { get; set; }

            /// <summary>
            /// 最大延迟(ms)
            /// </summary>
            public long MaxLatency { get; set; }

            /// <summary>
            /// 平均延迟(ms)
            /// </summary>
            public long AvgLatency { get; set; }

            /// <summary>
            /// 错误信息(如果有)
            /// </summary>
            public string Error { get; set; }
        }

        #endregion

        #region 进程信息

        /// <summary>
        /// 获取进程列表
        /// </summary>
        /// <returns>进程信息列表</returns>
        public static List<ProcessInfo> GetProcessList()
        {
            try
            {
                List<ProcessInfo> processList = new List<ProcessInfo>();
                Process[] processes = Process.GetProcesses();

                foreach (Process process in processes)
                {
                    try
                    {
                        ProcessInfo processInfo = new ProcessInfo
                        {
                            Id = process.Id,
                            Name = process.ProcessName,
                            MainWindowTitle = process.MainWindowTitle,
                            StartTime = process.StartTime,
                            RunningTime = DateTime.Now - process.StartTime,
                            MemoryUsageMB = Math.Round(process.WorkingSet64 / 1024.0 / 1024.0, 2),
                            Responding = process.Responding,
                        };

                        processList.Add(processInfo);
                    }
                    catch
                    {
                        // 忽略无法获取信息的进程
                    }
                }

                // 按内存使用量排序
                processList.Sort((p1, p2) => p2.MemoryUsageMB.CompareTo(p1.MemoryUsageMB));
                return processList;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取进程列表失败: {ex.Message}");
                return new List<ProcessInfo>();
            }
        }

        /// <summary>
        /// 进程信息类
        /// </summary>
        public class ProcessInfo
        {
            /// <summary>
            /// 进程ID
            /// </summary>
            public int Id { get; set; }

            /// <summary>
            /// 进程名称
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 主窗口标题
            /// </summary>
            public string MainWindowTitle { get; set; }

            /// <summary>
            /// 启动时间
            /// </summary>
            public DateTime StartTime { get; set; }

            /// <summary>
            /// 已运行时间
            /// </summary>
            public TimeSpan RunningTime { get; set; }

            /// <summary>
            /// 内存使用(MB)
            /// </summary>
            public double MemoryUsageMB { get; set; }

            /// <summary>
            /// 是否响应
            /// </summary>
            public bool Responding { get; set; }
        }

        #endregion

        #region 系统状态报告

        /// <summary>
        /// 生成系统状态报告
        /// </summary>
        /// <returns>系统状态报告</returns>
        public static SystemStatusReport GenerateStatusReport()
        {
            try
            {
                SystemStatusReport report = new SystemStatusReport();

                // 基本系统信息
                report.OSVersion = GetOSVersion();
                //report.ComputerName = GetComputerName();
                //report.UserName = GetUserName();
                //report.SystemUptime = GetSystemUptime();

                // CPU信息
                report.CpuUsage = GetCpuUsage();

                // 内存信息
                var memoryMetrics = GetMemoryUsage();
                report.MemoryTotal = memoryMetrics.Total;
                report.MemoryUsed = memoryMetrics.Used;
                report.MemoryUsagePercentage = memoryMetrics.UsagePercentage;

                // 磁盘信息
                report.DiskInfo = GetDiskInfo();

                // 网络信息
                //report.NetworkAdapters = GetNetworkAdapterInfo();

                // 获取前10个内存占用最多的进程
                //var allProcesses = GetProcessList();
                //report.TopProcesses = allProcesses.Take(10).ToList();

                // 设置报告时间
                report.ReportTime = DateTime.Now;

                return report;
            }
            catch (Exception ex)
            {
                _logger.Error($"生成系统状态报告失败: {ex.Message}");
                return new SystemStatusReport { Error = ex.Message };
            }
        }

        /// <summary>
        /// 系统状态报告类
        /// </summary>
        public class SystemStatusReport
        {
            /// <summary>
            /// 报告生成时间
            /// </summary>
            public DateTime ReportTime { get; set; }

            /// <summary>
            /// 操作系统版本
            /// </summary>
            public string OSVersion { get; set; }

            /// <summary>
            /// 计算机名称
            /// </summary>
            public string ComputerName { get; set; }

            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 系统运行时间(小时)
            /// </summary>
            public double SystemUptime { get; set; }

            /// <summary>
            /// CPU使用率(%)
            /// </summary>
            public float CpuUsage { get; set; }

            /// <summary>
            /// 总内存(MB)
            /// </summary>
            public ulong MemoryTotal { get; set; }

            /// <summary>
            /// 已用内存(MB)
            /// </summary>
            public ulong MemoryUsed { get; set; }

            /// <summary>
            /// 内存使用率(%)
            /// </summary>
            public uint MemoryUsagePercentage { get; set; }

            /// <summary>
            /// 磁盘信息
            /// </summary>
            public List<DiskInfo> DiskInfo { get; set; } = new List<DiskInfo>();

            /// <summary>
            /// 网络适配器信息
            /// </summary>
            public List<NetworkAdapterInfo> NetworkAdapters { get; set; } =
                new List<NetworkAdapterInfo>();

            /// <summary>
            /// 内存占用最多的进程列表
            /// </summary>
            public List<ProcessInfo> TopProcesses { get; set; } = new List<ProcessInfo>();

            /// <summary>
            /// 错误信息(如果有)
            /// </summary>
            public string Error { get; set; }
        }

        #endregion
    }
}
